package com.macro.mall.portal.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class WechatUtil {
    /**
     * 调用auth.code2Session接口，获取openid和session_key
     * @param code          code
     * @param appid          小程序的appid
     * @param appsecret          小程序的appsecret
     */
    public static Map<String,Object> getWxUSerOpenid(String code, String appid, String appsecret){
        //拼接url
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?");
        url.append("appid=");//appid设置
        url.append(appid);
        url.append("&secret=");//secret设置
        url.append(appsecret);
        url.append("&js_code=");//cede设置
        url.append(code);
        url.append("&grant_type=authorization_code");
        JSONObject jsonObject=null;
        try{
            CloseableHttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet((url.toString()));//构建一个GET请求
            CloseableHttpResponse response = client.execute(get);//提交get请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            jsonObject = JSON.parseObject(content);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
}
